package egovframework.npqs.pqi.mobile.activity.quarantineresult;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import egovframework.npqs.pqi.mobile.ActivityMain;
import egovframework.npqs.pqi.mobile.AppStatus;
import egovframework.npqs.pqi.mobile.BaseFragment;
import egovframework.npqs.pqi.mobile.R;
import egovframework.npqs.pqi.mobile.activity.PlaceOfficerActivity;
import egovframework.npqs.pqi.mobile.activity.RelationDiseasePestActivity;
import egovframework.npqs.pqi.mobile.activity.approve.ApproveDetail;
import egovframework.npqs.pqi.mobile.jsoncontent.ErrorItem;
import egovframework.npqs.pqi.mobile.jsoncontent.QuarantineResultDetailItem;
import egovframework.npqs.pqi.mobile.jsoncontent.listitem.DelaysayuListItem;
import egovframework.npqs.pqi.mobile.jsoncontent.listitem.QuarantineDetailListItem;
import egovframework.npqs.pqi.mobile.jsoncontent.listitem.QunCdItem;
import egovframework.npqs.pqi.mobile.jsoncontent.listitem.TypeListItem;
import egovframework.npqs.pqi.mobile.jsoncontent.listitem.ValidFlagListItem;
import egovframework.npqs.pqi.mobile.jsonparser.QuarantineResultDetailThread;
import egovframework.npqs.pqi.mobile.jsonparser.QuarantineResultDetailThread.QuarantineResultDetailThreadCallback;
import egovframework.npqs.pqi.mobile.jsonparser.QuarantineResultUpdateThread;
import egovframework.npqs.pqi.mobile.jsonparser.QuarantineResultUpdateThread.QuarantineResultUpdateThreadCallback;

//검역결과등록
public class QuarantineResultInsert extends BaseFragment implements OnClickListener
		, OnItemSelectedListener
		, QuarantineResultDetailThreadCallback
		, QuarantineResultUpdateThreadCallback{
	private View view;
	private TextView titleTxt; // 상단 타이틀
	private AppStatus myapp;
	private Context context;
	private String recNo, success, quranCd1, quranCd2;
	private ActivityMain am;
	private ImageButton menuBtn, homeBtn, loginBtn;

	private ImageButton upBtn, downBtn, searchBtn;
	
	private String prdlstCode, prdlstNm, hsCd, korNm, engNm;

	private EditText offCdEdit, requestNumEdit, quranNm2;// 검역신청검역지 코드 에디트
	private ListView listView;
	private QuarantineDetailListAdapter quarantineDetailListAdapter;

	private TextView headerTotTxt, navigation;
	private TextView resNo, resultProgrsNm, venNm, venRep, venTelNo;
	private TextView natNm, delayNm, delayRcognAt, photo_name;
	private ImageButton button3_1, button10_1, button10_2;
	private TextView button6_1, button6_2, button6_3;
	
	private Spinner content8_1, content11_1;
	private EditText insPlace, quranNm1, remark, content_1_2;
	private RelativeLayout detail_layout6;

	private QuarantineResultDetailItem quarantineResultItem;
	private QuarantineResultDetailThread quarantineThread;
	private QuarantineResultUpdateThread quarantineUpdateThread;
	private ArrayList<QuarantineDetailListItem> prodArrList;
	private ArrayList<ValidFlagListItem> validArrList;
	private ArrayList<DelaysayuListItem> delayArrList;
	private ArrayList<QunCdItem> quncdArrList;
	private ArrayList<TypeListItem> typeArrList;

	private ArrayAdapter<String> qunAdapter;
	private ArrayAdapter<String> typeAdapter;

	private ArrayList<String> spinDelayArrList, spinvalidArrList,
			spinQunArrList, spinTypeArrList;

	private Button footerBtn01, footerBtn02, footerBtn03, footerBtn04; // 하단 버튼
	
	private final static int MSG_QUARANTINE_COMPLETED = 0;
	private final static int MSG_QUARANTINE_ERROR = 1;
	private final static int MSG_NETWORK_ERROR = 2;
	private final static int MSG_QUARANTINE_UPDATE_COMPLETED = 3;

	//사진
	private RelativeLayout detail_layout13_1, photo_check_mgs;
	private ImageView photo_view, photo_view2;
	private ImageButton button_13_1, button_13_2;
	private String castString1, castString2;
	private Drawable drawable1, drawable2;
	private String url1, url2;

	private boolean firstLoad;
	private ArrayList<String> arrInsQty;
	
	//아답터 클래스
	TextView detail_list_seq, detail_list_trfclsf_cd, detail_list_hs_cd;
	TextView detail_list_itm_qty, detail_list_prod_name;
	EditText detail_list_ins_qty;
	Spinner detail_list_qun_cd, list_detail_spin;
	ImageButton search_cd_btn;
		
	//화물관리번호, hs코드
	private TextView text_hwa_no, text_bl_no;
	
	//하단 리스트 해더
	private LinearLayout list_header_Layout;
	
	private String mResult;
	
	/* G-MOBILE 변수*/
    private String temp;
    private String requestNum;
    
    JSONObject resultDetail = new JSONObject();
	JSONObject resultData = new JSONObject();
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		AppStatus.navigation.addPathLocation("수입검역결과등록");
		arrInsQty = new ArrayList<String>();
		firstLoad = true;
		if (view != null) {
			ViewGroup parent = (ViewGroup) view.getParent();
			if (parent != null)
				parent.removeView(view);
		} else {
			view = inflater.inflate(R.layout.activity_quarantine_result_detail,
					container, false);
			init();
		}

		return view;
	}
	
	private void init() {
		context = view.getContext();
		myapp = (AppStatus) context.getApplicationContext();
		myapp.startBroker(context);
		am = (ActivityMain) ActivityMain.am;
		
		//하단 리스트 해더
		list_header_Layout = (LinearLayout)view.findViewById(R.id.list_header_Layout);

		homeBtn = (ImageButton) view.findViewById(R.id.btnHome);
		homeBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				getActivity().onBackPressed();
			}
		});
		menuBtn = (ImageButton) view.findViewById(R.id.btnLeftMenu);
		menuBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				am.toggle();
			}
		});

		titleTxt = (TextView) view.findViewById(R.id.headerTitleText);
		titleTxt.setText("수입검역결과등록");
		
		navigation = (TextView)view.findViewById(R.id.navigation);
		navigation.setText(AppStatus.navigation.getPath());
		Log.i("AppStatus.navigation.getPath()->", AppStatus.navigation.getPath());
		
		offCdEdit = (EditText) view.findViewById(R.id.content_1_1);
		offCdEdit.setText(myapp.getLoginItem().getOffCd());

		requestNumEdit = (EditText) view.findViewById(R.id.content_1_2);

		searchBtn = (ImageButton) view.findViewById(R.id.search_btn);
		searchBtn.setOnClickListener(this);

		/*loginBtn = (ImageButton) view.findViewById(R.id.btnLogin);
		loginBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				myapp.appFinish(context);
			}
		});*/

		//searchState = false;
		listView = (ListView) view.findViewById(R.id.qua_detail_list);
		listView.setVisibility(View.GONE);
		quarantineDetailListAdapter = new QuarantineDetailListAdapter();

		footerBtn01 = (Button) view.findViewById(R.id.footer01Btn);
		footerBtn02 = (Button) view.findViewById(R.id.footer02Btn);
		footerBtn03 = (Button) view.findViewById(R.id.footer03Btn);
		footerBtn04 = (Button) view.findViewById(R.id.footer04Btn);
		
		resNo = (TextView) view.findViewById(R.id.resNo);
		resultProgrsNm = (TextView) view.findViewById(R.id.resultProgrsNm);
		venNm = (TextView) view.findViewById(R.id.venNm);
		venRep = (TextView) view.findViewById(R.id.venRep);
		venTelNo = (TextView) view.findViewById(R.id.venTelNo);
		natNm = (TextView) view.findViewById(R.id.natNm);
		delayNm = (TextView) view.findViewById(R.id.delayNm);
		delayRcognAt = (TextView) view.findViewById(R.id.delayRcognAt);

		button3_1 = (ImageButton) view.findViewById(R.id.button_3_1);
		button6_1 = (TextView) view.findViewById(R.id.button_6_1);
		button6_2 = (TextView) view.findViewById(R.id.button_6_2);
		button6_3 = (TextView) view.findViewById(R.id.button_6_3);
		button10_1 = (ImageButton) view.findViewById(R.id.button_10_1);
		button10_2 = (ImageButton) view.findViewById(R.id.button_10_2);

		content8_1 = (Spinner) view.findViewById(R.id.content_8_1);
		content11_1 = (Spinner) view.findViewById(R.id.content_11_1);
		insPlace = (EditText) view.findViewById(R.id.insPlace);
		quranNm1 = (EditText) view.findViewById(R.id.quranNm1);
		remark = (EditText) view.findViewById(R.id.remark);
		quranNm2 = (EditText) view.findViewById(R.id.quranNm2);
		content_1_2 = (EditText) view.findViewById(R.id.content_1_2); // 검역신청번호
		

		detail_layout6 = (RelativeLayout) view.findViewById(R.id.detail_layout6);
		//사진
		detail_layout13_1 = (RelativeLayout) view.findViewById(R.id.detail_layout13_1);
		photo_check_mgs = (RelativeLayout) view.findViewById(R.id.photo_check_mgs);
		photo_view = (ImageView) view.findViewById(R.id.photo_view);
		photo_view2 = (ImageView) view.findViewById(R.id.photo_view2);
		button_13_1 = (ImageButton) view.findViewById(R.id.button_13_1);
		button_13_2 = (ImageButton) view.findViewById(R.id.button_13_2);
		castString1="";
		castString2="";
		
		//화물관리번호, hs코드
		text_hwa_no = (TextView) view.findViewById(R.id.text_hwa_no);
		text_bl_no = (TextView) view.findViewById(R.id.text_bl_no);

		// 연락처 누르면 전화걸기
		venTelNo.setPaintFlags(venTelNo.getPaintFlags()
				| Paint.UNDERLINE_TEXT_FLAG);
		venTelNo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Uri n = Uri.parse("tel: " + venTelNo.getText());
				startActivity(new Intent(Intent.ACTION_DIAL, n));
			}
		});

		button6_1.setText(Html.fromHtml("<u>긴급제한</u>"));
		button6_2.setText(Html.fromHtml("<u>수입금지</u>"));
		button6_3.setText(Html.fromHtml("<u>관련병해충</u>"));
		
		//footerBtn01.setOnClickListener(this);
		footerBtn04.setOnClickListener(this);
		button6_1.setOnClickListener(this);
		button6_2.setOnClickListener(this);
		button6_3.setOnClickListener(this);
		button10_1.setOnClickListener(this);
		button10_2.setOnClickListener(this);
		
		//목록버튼 없애기..
		footerBtn01.setBackgroundResource(R.drawable.f_blank_sel);
		//에러나면 버튼막기
		footerBtn02.setBackgroundResource(R.drawable.f_blank_sel);
		footerBtn03.setBackgroundResource(R.drawable.f_blank_sel);
	}

	private void searchDetail(String requestNum) {
		myapp.showDialogNo(context);
		myapp.startBroker(context);
		this.requestNum = requestNum;
		temp = "조건검색";
		threadStart();

	}
	
	public void threadStart(){
		if("조건검색".equals(temp)){
    		quarantineThread = new QuarantineResultDetailThread(context, this, myapp.getLoginItem().getOffCd(), requestNum, AppStatus.getmUserId());
    		quarantineThread.start();
    	}
    	if("저장".equals(temp)){
    		quarantineUpdateThread = new QuarantineResultUpdateThread(context,
    				this, resultData.toString(), resultDetail.toString(), AppStatus.getmUserId());
    		quarantineUpdateThread.start();
    	}
	}
	
	private void layoutSetting() {
		resNo.setText(quarantineResultItem.getResNo());
		resultProgrsNm.setText(quarantineResultItem.getResultProgrsNm());
		venNm.setText(quarantineResultItem.getVenNm());
		venRep.setText(quarantineResultItem.getVenRep());
		venTelNo.setText(quarantineResultItem.getVenTelNo());
		natNm.setText(quarantineResultItem.getNatNm());
		delayNm.setText(quarantineResultItem.getDelayNm());
		delayRcognAt.setText(quarantineResultItem.getDelayRcognAt());
		insPlace.setText(quarantineResultItem.getInsPlace());
		remark.setText(quarantineResultItem.getRemark());
		//content10_1.setText(myapp.getLoginItem().getUserNm());
		if(firstLoad){
			if(quarantineResultItem.getQuranNm1().equals("")){
				quranNm1.setText(myapp.getLoginItem().getUserNm());
				quranCd1 = myapp.getLoginItem().getUserSn();
			}else{
				quranNm1.setText(quarantineResultItem.getQuranNm1());
				quranCd1 = quarantineResultItem.getQuranCd1();
			}
			quranNm2.setText(quarantineResultItem.getQuranNm2());
			quranCd2 = quarantineResultItem.getQuranCd2();
			firstLoad=false;
		}
		quranNm1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				quranNm1.setText("");
				quranCd1="";
			}
		});
		quranNm1.requestFocus();
		quranNm2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				quranNm2.setText("");
				quranCd2="";
			}
		});

		//사진보기
		if("".equals(quarantineResultItem.getImgResult1().trim())){
			url1="";
			castString1="";
		}else{
			url1 = myapp.cameraUtil.photoSetting(quarantineResultItem.getImgResult1()).replace("\\", "/");
			Log.i("url1 : ", url1);
			new yourTask().execute();
		}
		if("".equals(quarantineResultItem.getImgResult2().trim())){
			url2 = "";
			castString2="";
		}else{
			url2 = myapp.cameraUtil.photoSetting(quarantineResultItem.getImgResult2()).replace("\\", "/");
			new yourTask().execute();
		}
		button_13_1.setOnClickListener(this);
		button_13_2.setOnClickListener(this);
		
		/*if (!quarantineResultItem.getPzsCnt().equals("0")) { // 과태료 여부 안보이게
			button3_1.setVisibility(View.VISIBLE);
		}*/
		Log.i("PenCnt 긴급제한", quarantineResultItem.getPenCnt());
		if (!quarantineResultItem.getPenCnt().equals("0")) { // 긴급제한 여부 안보이게
			button6_1.setVisibility(View.VISIBLE);
		}
		Log.i("ExpCnt 수입 금지", quarantineResultItem.getExpCnt());
		if (!quarantineResultItem.getExpCnt().equals("0")) { // 수입금지 안보이게
			button6_2.setVisibility(View.VISIBLE);
		}
		Log.i("DbyhsCnt 관련병해충", quarantineResultItem.getDbyhsCnt());
		if (!quarantineResultItem.getDbyhsCnt().equals("0")) { // 관련병해충 안보이게
			button6_3.setVisibility(View.VISIBLE);
		}

		// 한줄 없애기
		if(!quarantineResultItem.getPenCnt().equals("0") ||
				!quarantineResultItem.getExpCnt().equals("0") ||
				!quarantineResultItem.getDbyhsCnt().equals("0")){	
			detail_layout6.setVisibility(View.VISIBLE);
		}

		validArrList = quarantineResultItem.getValidflagList();
		if (validArrList.size() > 0) {
			spinvalidArrList = new ArrayList<String>();
			for (int i = 0; i < validArrList.size(); i++) {
				spinvalidArrList.add(validArrList.get(i).getCodeNm());
			}
		}

		delayArrList = quarantineResultItem.getDelaysayuList();
		if (delayArrList.size() > 0) {
			spinDelayArrList = new ArrayList<String>();
			for (int i = 0; i < delayArrList.size(); i++) {
				spinDelayArrList.add(delayArrList.get(i).getCodeNm());
			}
		}

		quncdArrList = quarantineResultItem.getQunCdList();
		if (quncdArrList.size() > 0) {
			spinQunArrList = new ArrayList<String>();
			for (int i = 0; i < quncdArrList.size(); i++) {
				spinQunArrList.add(quncdArrList.get(i).getCodeNm());
			}
		}

		typeArrList = quarantineResultItem.getTypeList();
		if (typeArrList.size() > 0) {
			spinTypeArrList = new ArrayList<String>();
			for (int i = 0; i < typeArrList.size(); i++) {
				spinTypeArrList.add(typeArrList.get(i).getCodeNm());
			}
		}

		ArrayAdapter<String> delayAdapter = new ArrayAdapter<String>(context,
				R.layout.spinner_item, spinDelayArrList);

		ArrayAdapter<String> validAdapter = new ArrayAdapter<String>(context,
				R.layout.spinner_item, spinvalidArrList);

		delayAdapter.setDropDownViewResource(R.layout.spinner_item);
		validAdapter.setDropDownViewResource(R.layout.spinner_item);

		content8_1.setAdapter(validAdapter);
		content11_1.setAdapter(delayAdapter);

		for (int i = 0; i < validArrList.size(); i++) {
			if (validArrList.get(i).getCode()
					.equals(quarantineResultItem.getValidflag())) {
				content8_1.setSelection(i);
			}
		}

		for (int i = 0; i < delayArrList.size(); i++) {
			if (delayArrList.get(i).getCode()
					.equals(quarantineResultItem.getDelaysayu())) {
				content11_1.setSelection(i);
			}
		}

		footerBtn02.setOnClickListener(this);
		footerBtn03.setOnClickListener(this);
		footerBtn02.setBackgroundResource(R.drawable.foot_save_selector);
		footerBtn03.setBackgroundResource(R.drawable.foot_approval_selector);
		
		prodArrList = quarantineResultItem.getItems();
		
		for(int i=0; i<prodArrList.size(); i++){
			arrInsQty.add(i, prodArrList.get(i).getInsQty());
			Log.i("position", i+"");
		}
		Log.i("prodArrList.get(position).getInsQty()", arrInsQty.toString());
		Log.i("InsQty().size", arrInsQty.size()+"");
		
		headerTotTxt = (TextView) view.findViewById(R.id.header_tot);
		upBtn = (ImageButton) view.findViewById(R.id.header_up_btn);
		downBtn = (ImageButton) view.findViewById(R.id.header_down_btn);

		headerTotTxt.setText("총 품목:" + quarantineResultItem.getItemsResult() + "건");
		
		listView.setVisibility(View.VISIBLE);
		listView.setAdapter(quarantineDetailListAdapter);
		upBtn.setOnClickListener(this);
		downBtn.setOnClickListener(this);
		downBtn.performClick();
		//searchState = true;
	}
	
	private class yourTask extends AsyncTask<Integer, Void, Integer> {
	    @Override
	    protected void onPreExecute() {
	        super.onPreExecute();
	    }

	    @Override
	    protected Integer doInBackground(Integer... params) {
	        BitmapDrawable drawable = null;
	        Bitmap bitmap = null;
	        System.out.println("url1 : "+url1);
	        System.out.println("url2 : "+url2);
	        if(!"".equals(url1)){
	        	drawable1  =  myapp.cameraUtil.LoadImageFromWeb(url1);
	        	drawable = (BitmapDrawable)drawable1;
	        	bitmap = drawable.getBitmap();
	        	castString1 = myapp.cameraUtil.castByteArrayToString(myapp.cameraUtil.bitmapToByteArray(bitmap));
	        }
	        if(!"".equals(url2)){
	        	drawable2  =  myapp.cameraUtil.LoadImageFromWeb(url2); 
	        	drawable = (BitmapDrawable)drawable2;
	        	bitmap = drawable.getBitmap();
	        	castString2 = myapp.cameraUtil.castByteArrayToString(myapp.cameraUtil.bitmapToByteArray(bitmap));
	        }
	        return 0; 
	    }      

	    @Override
	    protected void onPostExecute(Integer result) {
	        super.onPostExecute(result);
	        if(!"".equals(castString1.trim())){
	        	detail_layout13_1.setVisibility(View.VISIBLE);
	        	photo_check_mgs.setVisibility(View.GONE);
	        	photo_view.setVisibility(View.VISIBLE);
	        	photo_view.setImageDrawable(drawable1);   
	 	        button_13_1.setVisibility(View.VISIBLE);
	        }
	        if(!"".equals(castString2.trim())){
	        	photo_view2.setVisibility(View.VISIBLE);
	        	photo_view2.setImageDrawable(drawable2);
	 	        button_13_2.setVisibility(View.VISIBLE);
	        }
	    }
	}
	
	// 첨부된 이미지뷰를 체크하여 둘다 없으면 레이아웃을 지운다.
	private void layoutCheck(ImageView v1, ImageView v2) {
		if (v1.getDrawable() == null && v2.getDrawable() == null) {
			detail_layout13_1.setVisibility(View.GONE);
			photo_check_mgs.setVisibility(View.VISIBLE);
		}
	}
	
	private void resultSave() {
		myapp.startBroker(context);
		resultDetail = new JSONObject();
		resultData = new JSONObject();
		JSONObject resultMaster = new JSONObject();
		JSONArray requestArray = new JSONArray();
		JSONObject obj;
		for (int i = 0; i < prodArrList.size(); i++) {
			Log.i("getItmQty", "getItmQty :: "+prodArrList.get(i).getItmQty());
			Log.i("getInsQty", "getInsQty :: "+prodArrList.get(i).getInsQty());

			if (Float.parseFloat(prodArrList.get(i).getInsQty()
					 .replace(",", "")) > Float.parseFloat(prodArrList.get(i)
					 .getItmQty().replace(",", ""))) {
				myapp.utilm.ShowDialog(context, "실패", "합격수량이 검역수량을 초과할 수 없습니다", 20);
				return;
			}

			try {
				obj = new JSONObject();
				obj.put("offCd", prodArrList.get(i).getOffCd());
				obj.put("recNo", prodArrList.get(i).getRecNo());
				obj.put("recSeq", prodArrList.get(i).getRecSeq());
				obj.put("insQty",prodArrList.get(i).getInsQty().replace(",", ""));
				obj.put("itmQty",prodArrList.get(i).getItmQty().replace(",", ""));
				obj.put("qunCd", prodArrList.get(i).getQunCd());
				obj.put("itemType", prodArrList.get(i).getItemType());
				obj.put("updNamCd", myapp.getLoginItem().getUserSn());
				
				Log.i("저장 품목변경값 : ", prdlstCode + " " + prdlstNm + " " + hsCd + " " + korNm + " " + engNm);
				obj.put("prdlstCode", prdlstCode);
				obj.put("prdlstNm", prdlstNm);
				obj.put("hsCd", hsCd);
				//obj.put("korNm", korNm);
				//obj.put("engNm", engNm);

				requestArray.put(obj);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		try {
			//현장검역관이 비어 있으면 널을 저장
			if(quranNm1.getText().toString().replace(" ", "").equals("")){
				quranCd1="";
			}
			if(quranNm2.getText().toString().replace(" ", "").equals("")){
				quranCd2="";
			}
			resultMaster.put("resOffCd", quarantineResultItem.getResOffCd());
			resultMaster.put("resNo", quarantineResultItem.getResNo());
			resultMaster.put("regType", quarantineResultItem.getRegType());
			resultMaster.put("offCd", quarantineResultItem.getOffCd());
			resultMaster.put("recNo", requestNumEdit.getText().toString());
			resultMaster.put("validflag", quarantineResultItem.getValidflag());
			resultMaster.put("passResrveReasonCd",quarantineResultItem.getDelaysayu()); /* 합격보류사유 */
			String re = remark.getText().toString();
			String fieArea = null;
			try {
				fieArea = new String(re.getBytes("ISO-8859-1"), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			resultMaster.put("fieArea", re); /* 검역장소 */
			resultMaster.put("quranCd1", quranCd1);
			resultMaster.put("quranCd2", quranCd2);
			resultMaster.put("remark", remark.getText().toString());
			resultMaster.put("updNamCd", myapp.getLoginItem().getUserSn());
			//사진
			if(castString1.equals("")&&!castString2.equals("")){
				castString1=castString2;
				castString2="";
				button_13_2.performClick();
			}
	        resultMaster.put("imgResult1", castString1);
			//resultMaster.put("imgResult1", bytePhoto);
			
	        //resultMaster.put("imgResult1", castString1);
	        
			resultMaster.put("imgResult2", castString2);
			resultMaster.put("fileId", quarantineResultItem.getFileId());
			resultData.put("resultMaster", resultMaster);
			resultDetail.put("resultDetail", requestArray);
			
		} catch (JSONException e) {
			e.printStackTrace();
		}

		myapp.showDialogNo(context);
		temp = "저장";
		threadStart();
		
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {

		// 조회버튼
		case R.id.search_btn:
			if (content_1_2.getText().toString().length() == 8) {
				searchDetail(requestNumEdit.getText().toString());
			} else {
				myapp.utilm.ShowDialog(context, "실패",
						"검역신청 번호 뒤 8자리를 입력해 주세요.", 20);
			}
			break;

		case R.id.footer01Btn: // 검역신청
			getActivity().onBackPressed();
			/*intent = new Intent(getActivity().getApplicationContext() , QuarantineRequestDetailActivity.class);
			intent.putExtra("recNo", quarantineResultItem.getRecNo());
			startActivity(intent);*/
			break;

		case R.id.footer02Btn: // 저장 버튼
			if("".equals(quranNm1.getText().toString())){
				myapp.utilm.ShowDialog(context, "실패", "1명 이상의 현장검역관명을 넣어 해주세요.", 20);
				return;
			}
			if(null==content11_1.getSelectedItem()){
				myapp.utilm.ShowDialog(context, "실패", "합격보유사유를 선택 해주세요.", 20);
				return;
			}
			if(resultProgrsNm.getText().toString().trim().equals("결재완료")){
				myapp.utilm.ShowDialog(context, "실패", "이미 저장 하였습니다.", 20);
				return;
			}
			resultSave();
			break;

		case R.id.footer03Btn: // 결재 버튼
			if (quarantineResultItem.getResultProgrsSt().equals("377002")&& quarantineResultItem.getDelaysayu().equals("342001")) {
				for (int i = 0; i < prodArrList.size(); i++) {
					if(!arrInsQty.get(i).replace(",", "").equals(prodArrList.get(i).getInsQty().replace(",", ""))){
						myapp.utilm.ShowDialog(context, "실패", "저장을 먼저 해주세요.",20);
						return;
					}
					
					if (Float.parseFloat(prodArrList.get(i).getInsQty().replace(",", "")) != Float.parseFloat(prodArrList.get(i).getItmQty().replace(",", ""))) {
						myapp.utilm.ShowDialog(context, "실패", "합격수량이 검역수량과 같아야 결재 가능 합니다.",20);
						return;
					}
				}
				intent = new Intent(getActivity().getApplicationContext(),
						ApproveDetail.class);
				intent.putExtra("resNo", quarantineResultItem.getResNo());
				intent.putExtra("resOffCd", quarantineResultItem.getResOffCd());
				intent.putExtra("value", "0");
				startActivity(intent);
			} else {
				myapp.utilm.ShowDialog(context, "실패", "저장을 먼저 해주세요.", 20);
			}
			break;

		case R.id.footer04Btn: // 사진버튼
			
			if(!castString1.trim().equals("") && !castString2.trim().equals("")){
				myapp.utilm.ShowDialog(context, "실패", "사진은 2장 까지 가능 합니다.", 20);
			}else{
				intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File("/sdcard/image.jpg")));
				startActivityForResult(intent, 3);
			}
			break;
			
		case R.id.button_13_1:
			photo_view.setImageDrawable(null);
			photo_view.setVisibility(View.GONE);
			button_13_1.setVisibility(View.GONE);
			castString1="";
			url1="";
			layoutCheck(photo_view, photo_view2);
			break;
			
		case R.id.button_13_2:
			photo_view2.setImageDrawable(null);
			photo_view2.setVisibility(View.GONE);
			button_13_2.setVisibility(View.GONE);
			castString2="";
			url2="";
			layoutCheck(photo_view, photo_view2);
			break;
			
		case R.id.header_up_btn:
			RelativeLayout.LayoutParams listParams = new RelativeLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, myapp.utilm.getDpToPixel(context, 400));
			listParams.addRule(RelativeLayout.ABOVE, R.id.bottom_layout);
			listView.setLayoutParams(listParams);
			break;
		case R.id.header_down_btn:
			RelativeLayout.LayoutParams listParams1 = new RelativeLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, myapp.utilm.getDpToPixel(context, 85));
			listParams1.addRule(RelativeLayout.ABOVE, R.id.bottom_layout);
			listView.setLayoutParams(listParams1);
			break;

		case R.id.button_10_1: // 현장검역관 + 이미지버튼 누르면
			intent = new Intent(getActivity().getApplicationContext(),
					PlaceOfficerActivity.class);
			intent.putExtra("userNm", quranNm1.getText().toString());
			startActivityForResult(intent, 1);
			break;

		case R.id.button_10_2:
			if (quranNm2.getText().toString()
					.equals(myapp.getLoginItem().getUserNm().toString())) {
				quranNm2.setText("");
			}
			intent = new Intent(getActivity().getApplicationContext(),
					PlaceOfficerActivity.class);
			intent.putExtra("userNm", quranNm2.getText().toString());
			startActivityForResult(intent, 2);
			break;

		case R.id.button_6_3: // 관련병해충
			intent = new Intent(getActivity().getApplicationContext(),
					RelationDiseasePestActivity.class);
			intent.putExtra("value", "1");
			intent.putExtra("natCd", quarantineResultItem.getNatCd());
			intent.putExtra("offCd", quarantineResultItem.getOffCd());
			intent.putExtra("recNo", quarantineResultItem.getRecNo());
			startActivity(intent);
			break;

		case R.id.button_6_2: // 긴급제한
			intent = new Intent(getActivity().getApplicationContext(),
					RelationDiseasePestActivity.class);
			intent.putExtra("value", "2");
			intent.putExtra("natCd", quarantineResultItem.getNatCd());
			intent.putExtra("offCd", quarantineResultItem.getOffCd());
			intent.putExtra("recNo", quarantineResultItem.getRecNo());
			startActivity(intent);
			break;

		case R.id.button_6_1: // 수입금지
			intent = new Intent(getActivity().getApplicationContext(),
					RelationDiseasePestActivity.class);
			intent.putExtra("value", "3");
			intent.putExtra("natCd", quarantineResultItem.getNatCd());
			intent.putExtra("offCd", quarantineResultItem.getOffCd());
			intent.putExtra("recNo", quarantineResultItem.getRecNo());
			startActivity(intent);
			break;

		default:
			break;
		}

	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MSG_QUARANTINE_COMPLETED:
        		if(quarantineResultItem.getTrnNm().equals("수입")){
        			list_header_Layout.setVisibility(View.VISIBLE);
        			myapp.utilm.InputKeybordHidden(context, requestNumEdit);
        			layoutSetting();
        		}else{
        			myapp.utilm.ShowDialog(context, "오류", "수출검역은 검색 할 수 없습니다", 10);
        			return;
        		}
				break;

			case MSG_QUARANTINE_ERROR:
				String errMsg = "";
				if (msg == null || msg.obj.toString().equals("")) {
					errMsg = "서버와의 연결에 실패하였습니다.";
				} else {
					errMsg = msg.obj.toString();
				}
				myapp.utilm.ShowDialog(context, "실패", errMsg, 20);
				System.out.println("========================================"+errMsg);
				break;

			case MSG_NETWORK_ERROR:
				myapp.utilm.ShowDialog(context, "실패", "네트워크에러", 20);
				break;
				
			case MSG_QUARANTINE_UPDATE_COMPLETED:
				new AlertDialog.Builder(context).setTitle("저장")
						.setMessage(success)
						.setPositiveButton("확인",new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										try {
											searchDetail(prodArrList.get(0).getRecNo());
										} catch (Exception e) {
										}
									}
								}).setCancelable(false).show();
				break;
				
			default:
				break;
			}
		}
	};

	class QuarantineDetailListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return prodArrList.size();
		}

		@Override
		public Object getItem(int position) {
			return prodArrList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			if (convertView == null || convertView != null) {
				LayoutInflater inflater = (LayoutInflater) context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.list_result_item2,
						parent, false);
			}

			detail_list_itm_qty = (TextView) convertView.findViewById(R.id.detail_list_itm_qty);
			detail_list_ins_qty = (EditText) convertView.findViewById(R.id.detail_list_ins_qty);
			detail_list_seq = (TextView) convertView.findViewById(R.id.detail_list_seq);
			detail_list_trfclsf_cd = (TextView) convertView.findViewById(R.id.detail_list_trfclsf_cd);
			detail_list_prod_name = (TextView) convertView.findViewById(R.id.detail_list_prod_name);
			detail_list_qun_cd = (Spinner) convertView.findViewById(R.id.detail_list_qun_cd);
			list_detail_spin = (Spinner) convertView.findViewById(R.id.list_detail_spin);
			detail_list_hs_cd = (TextView)convertView.findViewById(R.id.detail_list_hs_cd);

			detail_list_itm_qty.setText(prodArrList.get(position).getItmQty());
			detail_list_ins_qty.setText(prodArrList.get(position).getInsQty());
			detail_list_seq.setText(prodArrList.get(position).getRecSeq());
			detail_list_trfclsf_cd.setText(prodArrList.get(position).getPrdlstCode());
			detail_list_prod_name.setText(prodArrList.get(position)	.getPrdlstNm());
			detail_list_hs_cd.setText(prodArrList.get(position).getHsCd());
			
			/*search_cd_btn = (ImageButton)convertView.findViewById(R.id.search_cd_btn);
			search_cd_btn.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(getActivity().getApplicationContext(), ProdDetailActivity.class);
					intent.putExtra("prodCd", "no");
					startActivityForResult(intent, 4);
				}
			});*/
			
			detail_list_ins_qty.addTextChangedListener(new TextWatcher() {
				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {}
				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
				@Override
				public void afterTextChanged(Editable s) {
					prodArrList.get(position).setInsQty(s.toString());
				}
			});
			
			// qunAdapter.setDropDownViewResource(R.layout.spinner_item);
			// typeAdapter.setDropDownViewResource(R.layout.spinner_item);
			qunAdapter = new ArrayAdapter<String>(context,
					R.layout.spinner_item, spinQunArrList);
			typeAdapter = new ArrayAdapter<String>(context,
					R.layout.spinner_item, spinTypeArrList);
			detail_list_qun_cd.setAdapter(typeAdapter);
			list_detail_spin.setAdapter(qunAdapter);
			list_detail_spin.setOnItemSelectedListener(new OnItemSelectedListener() {
				@Override
				public void onItemSelected(AdapterView<?> parent, View view,
						int count, long id) {
					prodArrList.get(position).setQunCd(quncdArrList.get(count).getCode());
				}

				@Override
				public void onNothingSelected(AdapterView<?> parent) {}
			});
			
			detail_list_qun_cd.setOnItemSelectedListener(new OnItemSelectedListener() {
				@Override
				public void onItemSelected(AdapterView<?> parent, View view,
						int count, long id) {
					prodArrList.get(position).setItemType(typeArrList.get(count).getCode());
				}

				@Override
				public void onNothingSelected(AdapterView<?> parent) {}
			});
			
			for (int i = 0; i < quncdArrList.size(); i++) {
				if(quncdArrList.get(i).getCode().equals(prodArrList.get(position).getQunCd())){
					list_detail_spin.setSelection(i);
				}
			}
			
			for (int i = 0; i < typeArrList.size(); i++) {
				if(typeArrList.get(i).getCode().equals(prodArrList.get(position).getItemType())){
					detail_list_qun_cd.setSelection(i);
				}
			}
			
			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					listItemClickEvent(position);
				}
			});

			return convertView;
		}

		private void listItemClickEvent(final int position) {
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		switch (parent.getId()) {
		case R.id.content_8_1:
			quarantineResultItem.setValidflag(validArrList.get(position)
					.getCode());
			break;

		case R.id.content_11_1:
			quarantineResultItem.setDelaysayu(delayArrList.get(position)
					.getCode());
			break;

		default:
			break;
		}

	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
	}

	@Override
	public void OnQuarantineDetailCompleted(boolean isNetworkConntected,
			QuarantineResultDetailItem quarantineItem, String message) {
		//new
		Log.i("message-->", "message-->"+message);
		if(null != message && !"".equals(message)){
			mResult = message;
			reesultToast();
		}
		
		if (myapp.dialog != null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}

		if (!isNetworkConntected) { // 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}

		if (quarantineItem != null) {
			this.quarantineResultItem = quarantineItem;
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_COMPLETED;
			handler.sendMessage(msg);
		}

	}

	@Override
	public void OnQuarantineDetailError(ErrorItem errorItem) {
		if (myapp.dialog != null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}

		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_ERROR;
		if (errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		handler.sendMessage(msg);

	}

	@Override
	public void Onback() {
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case 1:
			if (resultCode == 1) {
				quranNm1.setText(data.getStringExtra("userNm"));
				quranCd1 = data.getStringExtra("userSn");

			} else {
				Log.i("resultCode", "resultCode  0 아님");
			}
			break;

		case 2:
			if (resultCode == 1) {
				quranNm2.setText(data.getStringExtra("userNm"));
				quranCd2 = data.getStringExtra("userSn");
			} else {
				Log.i("resultCode", "resultCode  0 아님");
			}
			break;

		case 3:
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 4;
			Bitmap captureBmp = BitmapFactory.decodeFile("/sdcard/image.jpg", options);
			
			if(captureBmp != null){
				Bitmap resized = Bitmap.createScaledBitmap(captureBmp, 740, 420, true);
				Matrix m = new Matrix();
				m.setRotate(90, (float) resized.getWidth() / 2, (float) resized.getHeight() / 2 );
				try{
					Bitmap b2 = Bitmap.createBitmap(resized, 0, 0, resized.getWidth(), resized.getHeight(), m, true);
					if(resized != b2){
						resized.recycle();
					}
					resized = b2;
				}catch (OutOfMemoryError ex){
				
				}
				detail_layout13_1.setVisibility(View.VISIBLE);
				photo_check_mgs.setVisibility(View.GONE);
				if(photo_view.getDrawable() == null){
					photo_view.setVisibility(View.VISIBLE);
					button_13_1.setVisibility(View.VISIBLE);
					photo_view.setImageBitmap(resized);
					castString1=(myapp.cameraUtil.castByteArrayToString(myapp.cameraUtil.bitmapToByteArray(resized)).trim());
				}else if(photo_view2.getDrawable() == null){
					photo_view2.setVisibility(View.VISIBLE);
					button_13_2.setVisibility(View.VISIBLE);
					photo_view2.setImageBitmap(resized);
					castString2=(myapp.cameraUtil.castByteArrayToString(myapp.cameraUtil.bitmapToByteArray(resized)).trim());
				}
				File f = new File("/sdcard/image.jpg");
				if(f.exists())
				{
					f.delete();
				}
			}
			break;

		//품목검색
		case 4:
			if(resultCode == 1){
				prdlstCode = data.getStringExtra("prdlstCode");	//품목코드
				prdlstNm = data.getStringExtra("prdlstNm");		//품목명
				hsCd = data.getStringExtra("hsCd");				//hs 코드
				korNm = data.getStringExtra("korNm");
				engNm = data.getStringExtra("engNm");
				Log.i("결과값 : ", prdlstCode + " " + prdlstNm + " " + hsCd + " " + korNm + " " + engNm);
				detail_list_trfclsf_cd.setText(prdlstCode);
				detail_list_hs_cd.setText(hsCd);
				detail_list_prod_name.setText(prdlstNm);
			}else{
				Log.i("resultCode","resultCode  0 아님");
			}
			break;
			
		default:
			break;
		}
	}

	@Override
	public void onResume() {
		//downBtn.performClick();
		if (myapp.isFinishState()) {
			((Activity) context).finish();
			myapp.setFinishState(false);
		}
		if(myapp.isDataDetailLoadState()){
			myapp.startBroker(context);
			searchBtn.performClick();
			myapp.setDataDetailLoadState(false);
		}
		if(myapp.isAbleHome()){
			homeBtn.performClick();
			myapp.setAbleHome(false);
		}
		super.onResume();
	}

	@Override
	public void onPause() {
		myapp.setFinishState(false);
		super.onPause();
	}
	
	@Override
	public void OnQuarantineResultUpdateCompleted(boolean isNetworkConntected,
			String result, String message) {
		Log.i("message-->", "message-->"+message);
		if(null != message && !"".equals(message)){
			mResult = message;
			reesultToast();
		}
		
		if (myapp.dialog != null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}

		if (!isNetworkConntected) { // 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}

		if (!result.equals("")) {
			this.success = result;
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_UPDATE_COMPLETED;
			handler.sendMessage(msg);
		}

	}

	@Override
	public void OnQuarantineResultUpdatelError(ErrorItem errorItem) {
		if (myapp.dialog != null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}

		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_ERROR;
		if (errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		handler.sendMessage(msg);
	}
	
	@Override
	public void onDestroyView() {
		super.onDestroyView();
		AppStatus.navigation.delPathLocation();
	}
	
	//new 토스트 창
	private void reesultToast() {
		am.runOnUiThread(new Runnable() {

            public void run() {
                Toast toast = Toast.makeText(context, mResult, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 50);
                toast.show();
            }
        });
    }
}